<template>
  <div id="app" class="app">
    <!-- 全局加载状态 -->
    <van-overlay :show="globalLoading" class="loading-overlay">
      <div class="loading-content">
        <van-loading size="24px" color="#1989fa" />
        <div class="loading-text">{{ loadingText }}</div>
      </div>
    </van-overlay>

    <!-- 路由视图 -->
    <router-view v-slot="{ Component, route }">
      <transition
        :name="route.meta.transition || 'slide-left'"
        mode="out-in"
        appear
      >
        <keep-alive :include="keepAliveComponents">
          <component :is="Component" :key="route.fullPath" />
        </keep-alive>
      </transition>
    </router-view>

    <!-- 全局提示 -->
    <van-notify v-model:show="notifyVisible" :type="notifyType" :message="notifyMessage" />
    
    <!-- 网络状态提示 -->
    <van-notify
      v-model:show="networkNotifyVisible"
      type="warning"
      message="网络连接已断开，请检查网络设置"
      :duration="0"
    />

    <!-- 版本更新提示 -->
    <van-dialog
      v-model:show="updateDialogVisible"
      title="发现新版本"
      :message="updateMessage"
      show-cancel-button
      confirm-button-text="立即更新"
      cancel-button-text="稍后提醒"
      @confirm="handleUpdate"
      @cancel="handleUpdateLater"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

// 全局加载状态
const globalLoading = computed(() => appStore.loading)
const loadingText = computed(() => appStore.loadingText)

// 需要缓存的组件
const keepAliveComponents = computed(() => appStore.keepAliveComponents)

// 全局提示
const notifyVisible = ref(false)
const notifyType = ref('success')
const notifyMessage = ref('')

// 网络状态
const networkNotifyVisible = ref(false)
const isOnline = ref(navigator.onLine)

// 版本更新
const updateDialogVisible = ref(false)
const updateMessage = ref('')

// 监听网络状态变化
const handleOnline = () => {
  isOnline.value = true
  networkNotifyVisible.value = false
  console.log('网络已连接')
}

const handleOffline = () => {
  isOnline.value = false
  networkNotifyVisible.value = true
  console.log('网络已断开')
}

// 处理版本更新
const handleUpdate = () => {
  window.location.reload()
}

const handleUpdateLater = () => {
  updateDialogVisible.value = false
  // 30分钟后再次提醒
  setTimeout(() => {
    checkForUpdates()
  }, 30 * 60 * 1000)
}

// 检查版本更新
const checkForUpdates = async () => {
  try {
    // 这里可以调用API检查是否有新版本
    // const response = await api.checkVersion()
    // if (response.data.hasUpdate) {
    //   updateMessage.value = response.data.updateMessage
    //   updateDialogVisible.value = true
    // }
  } catch (error) {
    console.error('检查更新失败:', error)
  }
}

// 全局事件监听
const setupGlobalListeners = () => {
  // 监听网络状态
  window.addEventListener('online', handleOnline)
  window.addEventListener('offline', handleOffline)
  
  // 监听页面可见性变化
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) {
      // 页面重新可见时，检查用户登录状态
      userStore.checkAuthStatus()
    }
  })
  
  // 监听路由变化
  router.beforeEach((to, from, next) => {
    // 设置页面标题
    if (to.meta.title) {
      document.title = `${to.meta.title} - RX在线教育平台`
    }
    
    // 检查登录状态
    if (to.meta.requiresAuth && !userStore.isLoggedIn) {
      next({ name: 'Login', query: { redirect: to.fullPath } })
    } else {
      next()
    }
  })
  
  // 监听路由错误
  router.onError((error) => {
    console.error('路由错误:', error)
    showNotify('页面加载失败，请重试', 'danger')
  })
}

// 显示全局提示
const showNotify = (message, type = 'success') => {
  notifyMessage.value = message
  notifyType.value = type
  notifyVisible.value = true
}

// 清理事件监听
const cleanupListeners = () => {
  window.removeEventListener('online', handleOnline)
  window.removeEventListener('offline', handleOffline)
}

// 初始化应用
const initApp = async () => {
  try {
    // 初始化用户状态
    await userStore.initAuth()
    
    // 初始化应用配置
    await appStore.initApp()
    
    // 检查版本更新
    if (import.meta.env.PROD) {
      setTimeout(checkForUpdates, 5000)
    }
  } catch (error) {
    console.error('应用初始化失败:', error)
  }
}

onMounted(() => {
  setupGlobalListeners()
  initApp()
})

onUnmounted(() => {
  cleanupListeners()
})

// 暴露方法给全局使用
window.$showNotify = showNotify
</script>

<style lang="scss" scoped>
.app {
  min-height: 100vh;
  background-color: var(--van-background-color);
}

.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  
  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    
    .loading-text {
      margin-top: 12px;
      font-size: 14px;
      color: var(--van-text-color);
    }
  }
}

// 路由过渡动画
.slide-left-enter-active,
.slide-left-leave-active {
  transition: all 0.3s ease;
}

.slide-left-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.slide-left-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

.slide-right-enter-active,
.slide-right-leave-active {
  transition: all 0.3s ease;
}

.slide-right-enter-from {
  transform: translateX(-100%);
  opacity: 0;
}

.slide-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from {
  transform: translateY(100%);
  opacity: 0;
}

.slide-up-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}
</style>